// utils/auth.js
const config = require('../config')
const jwt = require('jsonwebtoken')
const User = require('../models/User')

// 通过 jwt 中间件生成 token 字符串
exports.generateToken = user => {
	return jwt.sign({ id: user.id }, config.jwtSecretKey, {
		expiresIn: config.expiresIn
	})
}

// 验证 token 的中间件
exports.protect = async (req, res, next) => {
	const token = req.headers.authorization?.split(' ')[1]
	if (!token) return res.status(401).json({ error: 'Not authorized' })

	try {
		const decoded = jwt.verify(token, config.jwtSecretKey)
		req.user = await User.findById(decoded.id)
		next()
	} catch (err) {
		res.status(401).json({ error: 'Invalid token' })
	}
}
